﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic.ClassFactory;
using IssueCommon;
using ValidateCommon;
using Common;
using HtmlAgilityPack;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;

namespace RichECMS.ServerPages.Section
{
    public partial class UpdateSection : Base.SectionBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (State.LoginUser.ManagerCompetence > 2)
                {
                    this.trDataModel.Visible = false;
                    this.trDataPrototype.Visible = false;
                    this.trDataLabel.Visible = false;

                    this.trdatalabeltoolbar.Visible = false;
                    this.trdatamodeltoolbar.Visible = false;
                }
                else
                {
                    if (State.LoginUser.EnableParentPath)
                    {
                        trPath.Visible = true;
                        trPathInfo.Visible = true;
                    }
                    else
                    {
                        trPath.Visible = false;
                        trPathInfo.Visible = false;
                    }
                }

                if (Request.UrlReferrer == null)
                {
                    Response.Write("进入方式不正确");
                    Response.End();
                }
                else
                {
                    if (Request.UrlReferrer.Authority != Request.Url.Authority)
                    {
                        Response.Write("进入方式不正确");
                        Response.End();
                    }
                }
                this.trDataModel.Visible = false;
                this.trDataPrototype.Visible = false;
                this.trDataLabel.Visible = false;
                if (Request["section"] != null)
                {
                    if (ParamAuth.IsNumber(Request["section"].ToString().Trim()))
                    {
                        InitDataBind(Convert.ToInt32(Request["section"].Trim()));
                    }
                    else
                    {
                        AddChildSection.HRef = "###";
                        AddChildSection.InnerHtml = "";
                        Alert("参数错误");
                    }
                }
                else
                {
                    AddChildSection.HRef = "###";
                    AddChildSection.InnerHtml = "";
                    Alert("参数错误");
                }
                EchoTypeList();
                if (AppConfig.GetSectionReferEnabled())
                {
                    this.trReferOn.Visible = true;
                    MainSectionBind();
                }
                else
                {
                    this.trReferOn.Visible = false;
                }
            }
        }

        protected void EchoTypeList()
        {
            StringBuilder objbuilder = new StringBuilder();
            if (File.Exists(Server.MapPath("~/") + "ServerPages\\ExpandEditor\\ExpandEditor.config"))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(Server.MapPath("~/") + "ServerPages\\ExpandEditor\\ExpandEditor.config");
                XmlNode objExtenRootNode = xmlDoc.SelectSingleNode("/configuration/ExpandSet");
                if (objExtenRootNode != null)
                {
                    if (objExtenRootNode.HasChildNodes)
                    {
                        XmlNodeList objXMLNOdeList = objExtenRootNode.ChildNodes;
                        foreach (XmlNode objNodeTemp in objXMLNOdeList)
                        {
                            if (objNodeTemp.Attributes["type"] != null && objNodeTemp.Attributes["name"] != null)
                            {
                                string strType = objNodeTemp.Attributes["type"].Value;
                                string strName = objNodeTemp.Attributes["name"].Value;
                                objbuilder.AppendFormat("<span class='tylelistspan'><input type='radio' class='expandtyleradio' name='expandtyleradio' id='expandtyleradio{0}' etype='{1}' /><label for='expandtyleradio{2}'  >{3}</label></span> ", strType, strType, strType, strName);
                            }
                            else
                            {
                                Alert("扩展配置文件节点属性name或type存在异常");
                                return;
                            }
                        }
                    }
                }
            }
            Littypechoose.Text = objbuilder.ToString();
        }

        protected void MainSectionBind()
        {
            try
            {
                //绑定文章类型
                DropDownListMainSectionlist.Items.Clear();
                ListItem listitem = new ListItem("--请选择板块--", "-1");
                DropDownListMainSectionlist.Items.Add(listitem);
                using (SectionsFactory objFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objsection = objFactory.CreatorBySql("intParentID =0 and intWSID=" + State.intWSID + " order by intSortNo desc,  dtmInTime desc");
                    if (objsection != null)
                    {
                        for (int i = 0; i < objsection.Count; i++)
                        {
                            listitem = new ListItem(objsection.DataItem.chvSTCName + (objsection.DataItem.IstxtRemarksNull() ? "" : "(" + objsection.DataItem.txtRemarks + ")"),
                                                    objsection.DataItem.intSectionID.ToString());
                            DropDownListMainSectionlist.Items.Add(listitem);
                            objsection.SelectRow(i + 1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message.Replace("\r\n", ""));
            }
        }

        /// <summary>
        /// 页面输出
        /// </summary>
        private void InitDataBind(int intSectionId)
        {
            //绑定文章类型
            ListItem listitem = new ListItem("--请选择文章模版--", "-1");
            DropDownListArticle.Items.Add(listitem);
            using (TemplateFactory objFactory = new TemplateFactory())
            {
                BusinessLogic.BusinessRules.Template objTemplate = objFactory.CreatorBySql(" intType=" + (int)Utility.TemplateType.Article + " and intWSID=" + State.intWSID);
                if (objTemplate != null)
                {
                    for (int i = 0; i < objTemplate.Count; i++)
                    {
                        listitem = new ListItem(objTemplate.DataItem.chvName, objTemplate.DataItem.intTemplateID.ToString());
                        DropDownListArticle.Items.Add(listitem);
                        objTemplate.SelectRow(i + 1);
                    }
                }

                //绑定栏目类型
                listitem = new ListItem("--请选择栏目模版--", "-1");
                DropDownListSection.Items.Add(listitem);
                objTemplate = objFactory.CreatorBySql(" intType=" + (int)Utility.TemplateType.Section + " and intWSID=" + State.intWSID);
                if (objTemplate != null)
                {
                    for (int i = 0; i < objTemplate.Count; i++)
                    {
                        listitem = new ListItem(objTemplate.DataItem.chvName, objTemplate.DataItem.intTemplateID.ToString());
                        DropDownListSection.Items.Add(listitem);
                        objTemplate.SelectRow(i + 1);
                    }
                }

                using (SectionsFactory objSectionFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(intSectionId);
                    if (objSections != null)
                    {
                        LitSecstionName.Text = objSections.DataItem.IschvSTCNameNull() ? "" : objSections.DataItem.chvSTCName;
                        txtDateInTime.Text = objSections.DataItem.IsdtmInTimeNull() ? "" : objSections.DataItem.dtmInTime.ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
                        this.txtTitleCN.Value = objSections.DataItem.IschvSTCNameNull() ? "" : objSections.DataItem.chvSTCName;
                        this.txtTitleEn.Value = objSections.DataItem.IschvSTENameNull() ? "" : objSections.DataItem.chvSTEName;
                        this.txtSortNo.Value = objSections.DataItem.IsintSortNoNull() ? "" : objSections.DataItem.intSortNo.ToString();
                        txtRemark.Text = objSections.DataItem.IstxtRemarksNull() ? "" : objSections.DataItem.txtRemarks;

                        //发布路径设置
                        this.txtPerentPath.Text = objSections.DataItem.IschvParentPathNull() ? "" : objSections.DataItem.chvParentPath;
                        this.txtPageName.Value = objSections.DataItem.IschvPageNameNull() ? "" : objSections.DataItem.chvPageName;

                        //文章模型
                        foreach (ListItem item in DropDownListArticle.Items)
                        {
                            if (item.Value == objSections.DataItem.intArticleTemID.ToString())
                            {
                                DropDownListArticle.SelectedIndex = DropDownListArticle.Items.IndexOf(item);
                                break;
                            }
                        }
                        //栏目模型
                        DropDownListSection.ClearSelection();
                        if (DropDownListSection.Items.FindByValue(objSections.DataItem.intSectionTemID.ToString()) != null)
                        {
                            DropDownListSection.Items.FindByValue(objSections.DataItem.intSectionTemID.ToString()).Selected = true;
                        }
                        //文章状态
                        foreach (ListItem item in RadioButtonListArticle.Items)
                        {
                            if (item.Value == objSections.DataItem.intState.ToString())
                            {
                                RadioButtonListArticle.SelectedIndex = RadioButtonListArticle.Items.IndexOf(item);
                                break;
                            }
                        }
                        //栏目状态
                        foreach (ListItem item in RadioButtonListSection.Items)
                        {
                            if (item.Value == objSections.DataItem.intType.ToString())
                            {
                                RadioButtonListSection.SelectedIndex = RadioButtonListSection.Items.IndexOf(item);
                                break;
                            }
                        }
                        //引用状态 
                        if (!objSections.DataItem.IsintStateReferNull())
                        {
                            if (objSections.DataItem.intStateRefer == (int)Common.Utility.StateRefer.Yes)
                            {
                                this.CKBoxReferSection.Checked = true;
                                this.spanReferSectionName.Visible = true;
                                BusinessLogic.BusinessRules.Sections objSectionRefer = objSectionFactory.Creator(objSections.DataItem.intReferSectionID);
                                if (objSectionRefer != null)
                                {
                                    this.LitReferSectionName.Text = objSectionRefer.DataItem.chvSTCName + "(ID:" + objSectionRefer.DataItem.intSectionID + ")";
                                    ChangeSecHidden.Value = objSectionRefer.DataItem.intSectionID.ToString();
                                }

                                AddChildSection.Visible = false;
                            }
                            else
                            {
                                AddChildSection.HRef = "AddSection.aspx?section=" + Request["section"].Trim();
                            }
                        }
                        else
                        {
                            AddChildSection.HRef = "AddSection.aspx?section=" + Request["section"].Trim();
                        }
                    }
                    else
                    {
                        Alert("该文章不存在");
                    }
                }
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private bool ValidateValues()
        {
            bool bolIsValidate = true;
            if (this.txtTitleCN.Value.Trim().Length == 0)
            {
                Alert("请填写栏目中文名称");
                bolIsValidate = false;
            }
            if (!ParamAuth.IsDateTime(SqlCommon.SqlStringFilter(txtDateInTime.Text)))
            {
                Alert("请输入正确的发布时间格式");
                bolIsValidate = false;
            }
            if (DropDownListSection.SelectedValue.Trim() == "-1")
            {
                Alert("请选择栏目模版");
                bolIsValidate = false;
            }
            if (CKBoxReferSection.Checked)
            {
                if (!ParamAuth.IsNumber(this.ChangeSecHidden.Value.Trim()))
                {
                    Alert("请选择要引用的栏目");
                    bolIsValidate = false;
                }
            }

            if (State.LoginUser.EnableParentPath)
            {
                using (SectionsFactory objSectionsFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionsFactory.CreatorBySql(" chvParentPath ='" + this.txtPerentPath.Text.Trim().Replace("'", "") + "' and chvPageName ='" + this.txtPageName.Value.Trim().Replace("'", "")+"'");
                    if (objSections != null)
                    {
                        if (objSections.DataItem.intSectionID != Convert.ToInt32(Request["section"].Trim()))
                        {
                            Alert("该父路径和文件名已经被占用");
                            bolIsValidate = false;
                        }
                    }
                }
            }

            //if (DropDownListArticle.SelectedValue.Trim() == "-1")
            //{
            //    Alert("请选择文章模版");
            //    bolIsValidate = false;
            //}
            return bolIsValidate;
        }

        /// <summary>
        /// 提交数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SubmitBtnHander(object sender, ImageClickEventArgs e)
        {
            if (!ValidateValues())
            {
                if (CKBoxReferSection.Checked)
                {
                    this.trReferSelect.Visible = false;
                    using (SectionsFactory objFactory = new SectionsFactory())
                    {
                        try
                        {
                            BusinessLogic.BusinessRules.Sections objSections = objFactory.Creator(Convert.ToInt32(ChangeSecHidden.Value));
                            if (objSections != null)
                            {
                                LitReferSectionName.Text = objSections.DataItem.chvSTCName;
                            }
                        }
                        catch (Exception ex)
                        {
                            Alert(ex.Message.Replace("\r\n", ""));
                        }
                    }
                }
                return;
            }
            using (SectionsFactory objFactory = new SectionsFactory())
            {
                BusinessLogic.BusinessRules.Sections objSections = objFactory.Creator(Convert.ToInt32(Request["section"]));
                objSections.DataItem.chvSTCName = this.txtTitleCN.Value;
                objSections.DataItem.chvSTEName = this.txtTitleEn.Value.Trim().Equals("") ? Common.HzToPy.getSpell(this.txtTitleCN.Value.Trim()) : this.txtTitleEn.Value;
                if (CkboxAllowSyncDataModel.Checked == true)
                {
                    objSections.DataItem.chvDataPrototype = this.txtContent.Value;
                    objSections.DataItem.chvDataModel = this.txtdatamodle.Value;
                }
                if (CkboxAllowSyncDatLabel.Checked == true)
                {
                    objSections.DataItem.chvDataLabel = this.txtdataLabel.Value;
                }
                objSections.DataItem.intArticleTemID = Convert.ToInt32(DropDownListArticle.SelectedValue.Trim());
                objSections.DataItem.intSectionTemID = Convert.ToInt32(DropDownListSection.SelectedValue.Trim());
                objSections.DataItem.intState = Convert.ToInt32(RadioButtonListArticle.SelectedValue.Trim());
                objSections.DataItem.intType = Convert.ToInt32(RadioButtonListSection.SelectedValue.Trim());
                objSections.DataItem.dtmInTime = Convert.ToDateTime(txtDateInTime.Text);
                objSections.DataItem.intSortNo = Convert.ToInt32(txtSortNo.Value.Trim());
                objSections.DataItem.txtRemarks = txtRemark.Text;
                objSections.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                //发布路径设置
                objSections.DataItem.chvParentPath = this.txtPerentPath.Text.Trim().Replace("'", "");
                objSections.DataItem.chvPageName = this.txtPageName.Value.Trim().Replace("'", "");
                //设置栏目引用
                if (CKBoxReferSection.Checked)
                {
                    objSections.DataItem.intStateRefer = (int)Common.Utility.StateRefer.Yes;
                    int intReferSectionID = -1;
                    BusinessLogic.BusinessRules.Sections.FindSectionReferRoot(Convert.ToInt32(ChangeSecHidden.Value), ref intReferSectionID);
                    objSections.DataItem.intReferSectionID = intReferSectionID;
                }
                else
                {
                    objSections.DataItem.intStateRefer = (int)Common.Utility.StateRefer.No;
                    objSections.DataItem.intReferSectionID = -1;
                }
                objSections.Update();
            }
            AlertAndRedirectAndExecOther("修改栏目成功！", "UpdateSection.aspx?section=" + Request["section"].Trim(), false, "window.parent.refrashleft('" + Request["section"].Trim() + "');");
        }

        protected void DeleteThisSection(object sender, EventArgs e)
        {
            try
            {
                string strSpid = "";
                using (SectionsFactory objFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objFactory.Creator(Convert.ToInt32(Request["section"]));
                    if (objSections != null)
                    {
                        strSpid = objSections.DataItem.intParentID.ToString();
                        objSections.Delete(Convert.ToInt32(Request["section"]));
                    }
                }
                AlertAndRedirectAndExecOther("删除栏目成功！即将跳转，请稍候", "SectionsManage.aspx", false, "window.parent.refrashleft('" + (strSpid == "0" ? "" : strSpid) + "');");
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        protected void ImageButtonReset_Click(object sender, ImageClickEventArgs e)
        {

        }

        protected void ButtonSyncModle_Click(object sender, EventArgs e)
        {
            string htmlDoc = this.txtContent.Value;
            HtmlDocument htm = new HtmlDocument();
            htm.LoadHtml(htmlDoc);
            //构建a标签
            HtmlNodeCollection modleNode = htm.DocumentNode.SelectNodes("//span[@class='mycustomforms']/input");
            if (modleNode != null)
            {
                StringBuilder stringbuilderDataModle = new StringBuilder();
                stringbuilderDataModle.Append("<?xml version=\"1.0\"?>\r\n");
                stringbuilderDataModle.Append("<datamodel>\r\n");
                if (modleNode.Count > 0)
                {
                    for (int i = 0; i < modleNode.Count; i++)
                    {
                        if (modleNode[i].Attributes["id"] != null && modleNode[i].Attributes["title"] != null && modleNode[i].Attributes["stype"] != null)
                        {
                            Regex re = new Regex(@"^[a-zA-Z]+$", RegexOptions.IgnoreCase);
                            if (!re.IsMatch(modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower()))
                            {
                                Alert(string.Format("创建节点{0}发生错误，节点名ID必须使用字母并且不能以xml开头，不能使用其他字符", modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower()));
                                return;
                            }

                            if (modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower().Length > 2)
                            {
                                if (modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower().Substring(0, 3) == "xml")
                                {
                                    Alert(string.Format("创建节点{0}发生错误，节点名ID必须使用字母并且不能以xml开头，不能使用其他字符", modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower()));
                                    return;
                                }
                            }

                            stringbuilderDataModle.Append("    <" + modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower() + " description=\"" + modleNode[i].Attributes["title"].Value.ToString().Trim().ToLower() + "\" type=\"" + modleNode[i].Attributes["stype"].Value.ToString().Trim().ToLower() + "\" >\r\n");
                            stringbuilderDataModle.Append("    </" + modleNode[i].Attributes["id"].Value.ToString().Trim().ToLower() + ">\r\n");
                        }
                    }
                }
                stringbuilderDataModle.Append("</datamodel>\r\n");
                this.txtdatamodle.Value = stringbuilderDataModle.ToString();
                Alert("解析成功");
            }
            else
            {
                Alert("没有可供解析的html模版");
            }
        }

        protected void ButtonGetModel_Click(object sender, EventArgs e)
        {
            if (ParamAuth.IsNumber(Request["section"].ToString().Trim()))
            {
                using (SectionsFactory objSectionFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(Convert.ToInt32(Request["section"].Trim()));
                    if (objSections != null)
                    {
                        this.trDataModel.Visible = true;
                        this.trDataPrototype.Visible = true;
                        DataTable tblTmp = objSections.Data.Tables[0];
                        DataRow row = tblTmp.Rows[0];
                        this.txtdatamodle.Value = row["chvDataModel"] == DBNull.Value ? "" : objSections.DataItem.chvDataModel;
                        this.txtContent.Value = row["chvDataPrototype"] == DBNull.Value ? "" : objSections.DataItem.chvDataPrototype;
                    }
                    else
                    {
                        Alert("该栏目不存在");
                    }
                }
            }
            else
            {
                AddChildSection.HRef = "###";
                AddChildSection.InnerHtml = "";
                Alert("参数错误");
            }
        }

        protected void ButResetDataLabel_Click(object sender, EventArgs e)
        {
            this.trDataLabel.Visible = true;

            this.txtdataLabel.Value = RebuildDataLabel();
            Alert("已经重置");
        }

        protected void ButSetDataLabel_Click(object sender, EventArgs e)
        {
            if (ParamAuth.IsNumber(Request["section"].ToString().Trim()))
            {
                using (SectionsFactory objSectionFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(Convert.ToInt32(Request["section"].Trim()));
                    if (objSections != null)
                    {
                        this.trDataLabel.Visible = true;
                        DataTable tblTmp = objSections.Data.Tables[0];
                        DataRow row = tblTmp.Rows[0];
                        this.txtdataLabel.Value = row["chvDataLabel"] == DBNull.Value ? "" : objSections.DataItem.chvDataLabel;
                    }
                    else
                    {
                        Alert("该栏目不存在");
                    }
                }
            }
            else
            {
                AddChildSection.HRef = "###";
                AddChildSection.InnerHtml = "";
                Alert("参数错误");
            }
        }

        protected void SetRefer(object sender, EventArgs e)
        {
            if (this.CKBoxReferSection.Checked == true)
            {
                this.trReferSelect.Visible = true;
                this.spanReferSectionName.Visible = true;
            }
            else
            {
                this.spanReferSectionName.Visible = false;
                this.trReferSelect.Visible = false;
            }
        }
        protected void ReferSectionReselect(object sender, EventArgs e)
        {
            this.trReferSelect.Visible = true;
        }
    }
}